<template>
  <div class="back-to-top" @click="toTop" ref="toTop" v-if="topVisible">
    TOP
  </div>
</template>

<script>
import { throttle } from '@/utils/throttle.js'
export default {
  data() {
    return {
      topVisible: false
    }
  },

  mounted() {
    window.addEventListener('scroll', throttle(this.handleScroll, 500), true)
  },
  methods: {
    handleScroll() {
      let scrolltop = document.body.scrollTop

      if (scrolltop > 0) {
        this.topVisible = true
      } else {
        this.topVisible = false
      }
    },
    toTop() {
      // console.log(this.$refs.toTop)
      // console.log(document.body.scrollTop)
      let timer = setInterval(() => {
        document.body.scrollTop -= 50
        if (document.body.scrollTop === 0) {
          clearInterval(timer)
        }
      }, 10)
      // console.log(this.$refs.toTop.offsetTop)
      // document.body.scrollTop = 0
    }
  }
}
</script>

<style lang="scss" scoped>
.back-to-top {
  z-index: 30;
  position: fixed;
  right: 138px;
  bottom: 130px;
  width: 50px;
  height: 50px;
  background: #f5f5f5;
  border-radius: 50%;
  font-size: 20px;
  text-align: center;
  border: 1px solid #ccc;
  line-height: 50px;
  color: #333;
  &:hover {
    cursor: pointer;
    background: #ededed;
  }
}
</style>
